<div class="row animate fadeIn">
    <form id="add_invoice_form" class="form-horizontal"  method="post">
        <input type="hidden" name="hidden_invoice_id" id="h_inv_id">
        <input type="hidden" name="hidden_address_id" id="h_addressINV_id">
        <input type="hidden" name="hidden_chglist_id" id="h_chglistINV_id">
        <input type="hidden" name="hidden_acct_num"   id="h_acctINV_id">
        <input type="hidden" name="hidden_type_code"  id="h_type_code">

        <div class="ibox-title" style="border:none;"><h5 style="color: #00afef"><i>Add Invoice</i></h5>
            <div class="ibox-tools">    
                <button  id="sads" class="btn btn-sm btn-primary save-btn-tab">Save</button>
                <a id = "cancel_add" class="btn btn-sm btn-outline btn-info cancel-btn-tab">Cancel</a>
            </div>
        </div>
        <div class="ibox-content">   
          <div class="form-group">
              <label class="col-lg-2 control-label">Account No</label>
            <div class="col-lg-5">
              <select class="chosen-select" name="acct_no" id="a_n">
              <option value=""></option>
                <?php foreach ($customers as $cus) { ?>
                  <option value="<?php echo $cus->account_id; ?>" ><?php echo $cus->acct_num."( ".$cus->acct_name." )"; ?></option>
                <?php } ?>
              </select>
            </div>
              <label class="col-lg-2 control-label">Invoice No</label>
            <div class="col-lg-3">
              <input type="text" name="inv_num" class="form-control" value="<?php echo $invoice_num[0]->invoice_num; ?>" readonly>
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-2 control-label">Account Type</label>
            <div class="col-lg-5">
              <input type="text" id="a_t" name="acct_type" class="form-control" readonly>
            </div>
              <label class="col-lg-2 control-label">Invoice Date</label>
            <div class="col-lg-3">
              <input type="text" name="inv_date" class="form-control" value="<?php echo date('d-M-Y'); ?>" readonly>
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-2 control-label">Customer Name</label>
            <div class="col-lg-5">
              <input type="text" id="c_n" name="cus_name" class="form-control" readonly>
            </div>
              <label class="col-lg-2 control-label">GL Date</label>
            <div class="col-lg-3">
              <input type="text" name="inv_glDate" class="form-control" value="<?php echo date('d-M-Y'); ?>" readonly>
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-2 control-label">Billing Address</label>
            <div class="col-lg-5">
              <input type="text" id="b_a" name="bill_add" class="form-control" readonly></input>
            </div>
              <label class="col-lg-2 control-label">Due Date</label>
            <div class="col-lg-3">
              <input type="search" name="due_date" id="d_d" class="form-control">
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-2 control-label">Charge List</label>
            <div class="col-lg-5">
              <input type="text" id="c_l" name="chg_list" class="form-control" readonly>
            </div>
              <label class="col-lg-2 control-label">Previous Balance</label>
            <div class="col-lg-3">
              <input type="text" name="prev_bal" class="form-control">
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-2 control-label">Receivable Acct</label>
            <div class="col-lg-5">
              <select class="chosen-select" name="rec_acct">
                <?php foreach ($rec_acct as $rec_types) { ?>
                  <option value="<?php echo $rec_types->account_id; ?>" ><?php echo $rec_types->acct_code." : ".$rec_types->acct_name; ?></option>
                <?php } ?>
              </select>
            </div>
              <label class="col-lg-2 control-label">Invoice Status</label>
            <div class="col-lg-3">
              <select style="width: 159px;" class="chosen-select" name="inv_stat">
                <?php foreach ($inv_status as $lookup_stat) { ?>
                  <option value="<?php echo $lookup_stat->lookup_code; ?>" <?php echo($lookup_stat->lookup_code == "INC" ? 'selected' : ''); ?>><?php echo $lookup_stat->meaning; ?></option>
                <?php } ?>
              </select>
            </div>
          </div>
          <div class="form-group">
              <label class="col-lg-2 control-label">Description</label>
            <div class="col-lg-5">
              <input type="text" name="inv_desc" class="form-control">
            </div>
              <label class="col-lg-2 control-label">Invoice Total</label>
            <div class="col-lg-3">
              <input type="text" name="inv_total" class="form-control" value="0" readonly>
            </div>
          </div>
          <div class="form-group">
            <label class="col-lg-2 control-label">Invoice Type</label>
            <div class="col-lg-5">
              <select class="chosen-select" name="inv_type">
                <?php foreach ($invoice_t as $inv_t) { ?>
                  <option value="<?php echo $inv_t->lookup_code; ?>" ><?php echo $inv_t->lookup_code." : ".$inv_t->meaning; ?></option>
                <?php } ?>
              </select>
            </div>
              <label class="col-lg-2 control-label">Invoice Balance</label>
            <div class="col-lg-3">
              <input type="text" name="inv_bal" class="form-control" value="0" readonly>
            </div>
          </div>
          
        </div>
    </form>
<!--  -->
    <form id="invoice_inline_form">
      <input type="hidden" name="inline_invoice_id" id="inline_inv_id">
      <table id="invoice_tbl" class="table table-bordered" style="width:99%;">
        <thead>
          <tr>
            <th style="width:50px;">Line</th>
            <th style="">Item #</th>
            <th style="">Description</th>
            <th style="width:90px;">Quantity</th>
            <th style="width:150px;">Unit of Measure</th>
            <th style="width:50px;">Unit Price</th>
            <th style="width:50px;">TAX</th>
            <th style="width:70px;">Amount</th>
            <th style="width:50px;">Action</th>
          </tr>   
          <tr>
            <td style="margin:0px;padding:0px;">
              <input type="text" id="line_num" name="inline_num" class="form-control-custom" value="" readonly>
            </td>   
            <td style="margin:0px;padding:0px;">
              <select id="inv_chg_code" class="chosen-select" name="inline_invchg">
                <option value="">--</option>
              </select>
            </td>
            <td style="margin:0px;padding:0px;">
              <input type="text" id="inline_desc" name="inline_desc" class="form-control-custom" value="">
            </td>
            <td style="margin:0px;padding:0px;">
              <input type="text" id="" name="inline_quantity" class="form-control-custom" value="">
            </td>
            <td style="margin:0px;padding:0px;">
              <select class="chosen-select" name="inline_uom">
                <?php foreach ($uom as $uoms) { ?>
                  <option value="<?php echo $uoms->uom_code; ?>" ><?php echo $uoms->uom_name; ?></option>
                <?php } ?>
              </select>
            </td>
            <td style="margin:0px;padding:0px;">
              <input type="text" id="inline_rate" name="inline_rate" class="form-control-custom" value="">
            </td>
            <td style="margin:0px;padding:0px;">
              <input type="text" id="" name="inline_tax" class="form-control-custom" value="0">
            </td>
            <td style="margin:0px;padding:0px;">
              <input type="text" id="" name="inline_amount" class="form-control-custom" value="" readonly>
            </td>
            <td style="margin:0px;padding:0px;">
              <button style="width:100%;" class="btn btn-white" id=""><i class="fa fa-plus success"></i></button>
            </td>        
          </tr>
        </thead>
      </form>
        <tbody id="tbl_invoice" class="animate fadeIn">
        </tbody>
    </table> 

</div>
<script>
$(document).ready(function () {
    $('#add_invoice_form').data('serialize',$('#add_invoice_form').serialize());
    var rowline = $('#invoice_tbl >tbody >tr').length;
    var chg_elements = new Array();
    $('#line_num').val(rowline+1);

    $('#invoice_tbl').show();
    $(".chosen-select").chosen({width:"100%;"});
    $('.i-checks').iCheck({
        checkboxClass: 'icheckbox_square-green',
        radioClass: 'iradio_square-green',
    });
      
      $('#a_n').change(function(){
        $.ajax({
            type: "POST",
            url: "<?php echo base_url($this->session->userdata('forajax').'/get_account_data'); ?>",
            data: {"account": $('#a_n').val()},
            dataType: 'json',
        success: function(data){
                  $('#a_t').val(data.result1[0].meaning);     $('#c_n').val(data.result1[0].entity_name);
                  $('#b_a').val(data.result1[0].address);       $('#c_l').val(data.result1[0].list_name);

                  $('#h_addressINV_id').val(data.result1[0].address_id);
                  $('#h_chglistINV_id').val(data.result1[0].list_id);
                  $('#h_type_code').val(data.result1[0].acct_type);
                  chg_elements = new Array();  chg_elements = data.result2;
                  console.log(chg_elements);
                }      
        });
       $('#h_acctINV_id').val($('#a_n option:selected').html());
      });

      $('#inv_chg_code').change(function(){
        for(var i = 0; i <= chg_elements.length; i++){
          if($(this).val() == chg_elements[i].item_id){
             $('#inline_desc').val(chg_elements[i].description);
             $('#inline_rate').val(chg_elements[i].unit_selling_price);
          }
        }
      });

      $.validator.setDefaults({ ignore: ":hidden:not(select)" })
      $('#add_invoice_form').validate({
        rules:{
          acct_no    : {
            required : true
          },
          rec_acct   : {
            required : true
          },
          due_date   : {
            required : true
          }
        },submitHandler: function(form){
            $.ajax({
                type: "POST",
                url: "<?php echo base_url($this->session->userdata('forajax').'/insert_invoice'); ?>",
                data: $('#add_invoice_form').serialize(),
                dataType: 'json',
            success: function(data){
                if(data[0].error == 1){
                    notifymsg("danger",data[0].msg);
                }else{
                    notifymsg("success",". . Invoice added succesfully");
                    $('#h_inv_id').val(data[0].id); $('#inline_inv_id').val(data[0].id);
                    $('#invoice_tbl').show();    
                    $('#add_invoice_form').find('input, button').attr('disabled','disabled');    
                    $('#add_invoice_form').find('.chosen-select').prop('disabled', true).trigger("chosen:updated");
                    var trHTML = "";
                    trHTML += '<option value="">--</option>';
                    $.each(chg_elements, function(i, item) {
                        trHTML += '<option value="'+ chg_elements[i].item_id +'">'+ chg_elements[i].item_num +'</option>';
                    });
                    $('#inv_chg_code').empty().trigger("chosen:updated");
                    $('#inv_chg_code').append(trHTML).trigger("chosen:updated");
                    $('#cancel_add').html('Complete');
                }
              }
            });
         }
      });
      
      $('input[name="inline_rate"] , input[name="inline_quantity"]').change(function(){
          $('input[name="inline_amount"]').val($('input[name="inline_rate"]').val() * $('input[name="inline_quantity"]').val());
      });


      $('#invoice_inline_form').validate({
        rules:{
          inline_quantity : {
            required : true,
            number : true
          },
          inline_amount : {
            required : true
          }
        },submitHandler: function(form){
                    $.ajax({
                        type: "POST",
                        url: "<?php echo base_url($this->session->userdata('forajax').'/insert_invoice_inline'); ?>",
                        data: $('#invoice_inline_form').serialize(),
                        dataType: 'json',
                    success: function(data){
                        if(data[0].error == 1){
                            notifymsg("danger",data[0].msg);
                        }else{
                          $('#tbl_invoice').empty();
                          notifymsg("success",". . .Invoice inline added");
                          var total = parseInt($('input[name="inline_amount"]').val()) + parseInt($('input[name="inv_total"]').val());
                          update_invoiceBAL(total,$('#inline_inv_id').val());
                          $('input[name="inv_total"] , input[name="inv_bal"]').val(parseInt($('input[name="inv_total"]').val()) + parseInt($('input[name="inline_amount"]').val()));
                          var trHTML = '';
                          $.each(data, function(i, item) {
                              trHTML += '<tr><td>' + data[i].line_num + '</td><td text-align:right;>' + data[i].item_num + '</td><td text-align:right;>' + data[i].description + '</td><td text-align:right;>' + data[i].usage_qty + '</td><td text-align:right;>' + data[i].uom_name + '</td><td text-align:right;>' + data[i].unit_selling_price + '</td><td text-align:right;>' + data[i].tax_amt + '</td><td text-align:right;>' + data[i].line_amt + '</td><td></td></tr>';
                          });
                          $('#tbl_invoice').append(trHTML);
                          var nxt_lineNum = $('#line_num').val();
                          $('#invoice_inline_form')[0].reset();
                          $('#line_num').val(parseInt(nxt_lineNum) + 1);
                           $('#inv_chg_code').trigger('change');
                        }
                      }
                    });         
          }
      });
      
      function update_invoiceBAL(amount,id){
          $.ajax({
                type: "POST",
                url: "<?php echo base_url($this->session->userdata('forajax').'/update_invoice_totalBAL'); ?>",
                data: {"invoice_id": id , "amount": amount},
                dataType: 'json',
              success: function(data){
                
                }
            });
      }

      $('#d_d').datepicker({
          keyboardNavigation: false,
          forceParse: false,
          autoclose: true,
          format: "dd-M-yyyy"
      });
      function alert_cancel(){
            if($('#add_invoice_form').serialize()!=$('#add_invoice_form').data('serialize')){
                swal({
                    title: "Are you sure?",
                    text: "Your work will not be save",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Leave",
                    cancelButtonText: "Stay",
                    closeOnConfirm: true,
                    closeOnCancel: true },
                function (isConfirm) {
                    if (isConfirm) {
                        close_add(); active_search();
                        notifymsg("hide","hide");
                    } else {
                        swal("Cancelled");
                    }
                });
                }else{
                close_add(); active_search();
                notifymsg("hide","hide");
            }
        } 
        function alert_complete(){
                swal({
                    title: "Finished Adding ?",
                    text: "Are you sure you want to finish ?",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Leave",
                    cancelButtonText: "Stay",
                    closeOnConfirm: true,
                    closeOnCancel: true },
                function (isConfirm) {
                    if (isConfirm) {
                        close_add(); active_search();
                        notifymsg("hide","hide");
                    } else {
                        swal("Cancelled");
                    }
                });
        }


        $('#cancel_add').click(function () {
            if($('#cancel_add').html() == "Complete"){
            alert_complete();
          }else{            
            alert_cancel();
          }
         });
        $('#addX').click(function(){
            alert_cancel();        
       });

});
</script>